package com.bjc.platform.spring.aspect;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bjc.platform.Constants;
import com.bjc.platform.model.AdmLog;
import com.bjc.platform.model.CustomUserDetails;
import com.bjc.platform.repository.AdmLogRepo;
import com.bjc.platform.repository.AdmUserRepo;
import com.bjc.platform.util.IpUtil;
import com.bjc.platform.util.StaticMethod;

@Component
//@Aspect
public class RequestHandlerLogAspect {

	@Autowired
	private AdmLogRepo admLogRepo;

	@Autowired
	private AdmUserRepo admUserRepo;

	/**
	 * advice for request mapping handler in springmvc controller
	 * 
	 * @param jp
	 * @return
	 * @throws Throwable
	 */
	//@Around("execution(* org.springframework.web.servlet.HandlerAdapter.handle(..))")
	public Object around(ProceedingJoinPoint jp) throws Throwable {

		HttpServletRequest request = (HttpServletRequest) jp.getArgs()[0];
		// HttpServletResponse response = (HttpServletResponse)jp.getArgs()[1];
		// HandlerMethod handlerMethod = (HandlerMethod)jp.getArgs()[2];

		CustomUserDetails user = StaticMethod.getUser();

		AdmLog admLog = null;
		Object result = null;
		long timeUsed = 0;
		String url = request.getRequestURI();
		String ip = IpUtil.getIpAddr(request);
		try {
//			// 保存进入的日志
//			admLog = new AdmLog();
//			admLog.setSource(ip);
//			admLog.setType("INFO");
//			admLog.setUrl(url);
//			admLog.setFuncName("");
//			admLog.setDescription("开始......");
//			admLog.setLogTime(new Date());
//			admLog.setUserId(user.getId());
//			admLogRepo.save(admLog);

			// 调用处理并计时
			long startTime = System.currentTimeMillis();
			result = jp.proceed();
			long endTime = System.currentTimeMillis();
			timeUsed = endTime - startTime;
		} catch (Exception e) {

			// 保存出错日志
			admLog = new AdmLog();
			admLog.setSource(ip);
			admLog.setType("ERROR");
			admLog.setUrl(url);
			admLog.setFuncName("");
			
			ByteArrayOutputStream buf = new ByteArrayOutputStream();//新建一个数组节点流
			PrintStream pw = new PrintStream(buf, true);//新建一个PrintWriter的处理流
			e.printStackTrace(pw);//将字符串序列化写入节点流
			admLog.setDescription(buf.toString());
			pw.close(); 
			
			admLog.setLogTime(new Date());
			admLog.setUserId(user.getId());
			admLogRepo.save(admLog);

			throw e;
		} finally {

		}

		if(!url.contains(Constants.RANDCODE_IMG_URL)){
			// 保存完成日志
			admLog = new AdmLog();
			admLog.setSource(ip);
			admLog.setType("INFO");
			admLog.setUrl(url);
			admLog.setFuncName("");
			admLog.setDescription("完成，共耗时" + timeUsed + "毫秒。");
			admLog.setLogTime(new Date());
			admLog.setUserId(user.getId());
			admLogRepo.save(admLog);
		}

		return result;
	}
}
